package main

import (
	"context"
	"fmt"
	"github.com/panjf2000/ants/v2"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"go-iot-gateway/internal/app"
	sys_contant "go-iot-gateway/internal/sys/contant"
	"os/signal"
	"syscall"
	"time"
)

var HomeDir *string

func startCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "start",
		Short: "启动iot 网关服务",
		Long:  `启动iot 网关服务`,
		Run: func(cmd *cobra.Command, args []string) {
			startRun(*HomeDir)
		},
	}
	HomeDir = cmd.Flags().StringP("home-dir", "d", "", "家目录")

	return cmd
}

//func globalError(err error) {
//	logrus.Error("系统崩溃了>>>>>>")
//	logrus.Error(err)
//}

func startRun(homeDir string) {
	defer func() {
		ants.Release()
		logrus.Info("系统退出完成!!!")
	}()
	// Create context that listens for the interrupt signal from the OS.
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	err := app.Init(ctx, homeDir)
	if err != nil {
		logrus.Error(err)
		fmt.Println("系统初始化失败")
		return
	}

	err = app.Start()
	if err != nil {
		logrus.Error(err)
		fmt.Println("系统启动失败")
		return
	}

	banner := "                    _       _                     _                           \n                   (_)     | |                   | |                          \n   __ _  ___ ______ _  ___ | |_ ______ __ _  __ _| |_ _____      ____ _ _   _ \n  / _` |/ _ \\______| |/ _ \\| __|______/ _` |/ _` | __/ _ \\ \\ /\\ / / _` | | | |\n | (_| | (_) |     | | (_) | |_      | (_| | (_| | ||  __/\\ V  V / (_| | |_| |\n  \\__, |\\___/      |_|\\___/ \\__|      \\__, |\\__,_|\\__\\___| \\_/\\_/ \\__,_|\\__, |\n   __/ |                               __/ |                             __/ |\n  |___/                               |___/                             |___/ "
	fmt.Println(banner)
	fmt.Println("")
	fmt.Println("VERSION", sys_contant.APP_VERSION)
	fmt.Println("GO_VERSION", sys_contant.GO_VERSION)
	fmt.Println("RUNTIME", time.Now().Format("2006-01-02 15:04:05"))
	fmt.Println("\n\n")

	// Listen for the interrupt signal.
	<-ctx.Done()

	logrus.Info("系统正在退出....")

	// Restore default behavior on the interrupt signal and notify user of shutdown.
	stop()

	//最多等5秒关闭系统
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := app.Shutdown(ctx); err != nil {
		logrus.Fatal("Server forced to shutdown: ", err)
	}

	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	//quit := make(chan os.Signal)
	//signal.Notify(quit, os.Interrupt)
	//<-quit

	<-ctx.Done()
}
